<?php
	include dirname(__FILE__).'/common.php';
	include_once ROOT_PATH.'include/simple_html_dom.php';
	Class queryTSRC {
		public $cookieFile;
		public $header;
		public $value;
		public $cookie;
		public $now;
		public $all;

		public function __construct(){
			$this -> now = 1;
			$this -> cookieFile = './cookie';
			$this->headers = array(
					'Pragma: no-cache',
					'Cache-Control: no-cache',
					'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
					'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
					'Accept-Language: zh-CN,zh;q=0.8,en;q=0.6',
					'Connection: keep-alive',
					'Host: www.tsrcw.com',
					'Origin: http://www.tsrcw.com',
					'Referer: http://www.tsrcw.com/hr/company/login.aspx',
					'Upgrade-Insecure-Requests: 1',
			);
			$this -> cookie = 'ASP.NET_SessionId=tru2ezb540z5ranmmsgincym; ctype=company; cnc1=2825; cnc2=dexiang; cnc4=%e5%94%90%e5%b1%b1%e4%ba%ba%e6%89%8d; cvip=1; cname=%e5%94%90%e5%b1%b1%e5%b8%82%e4%b8%b0%e6%b6%a6%e5%8c%ba%e5%be%b7%e7%a5%a5%e5%95%86%e8%b4%b8%e6%9c%89%e9%99%90%e5%85%ac%e5%8f%b8; CNZZDATA1282693=cnzz_eid%3D128656101-1468395284-%26ntime%3D1468400685';
		}

		public function login($url,$arr){
			$post_list = '';
			foreach($arr as $key => $val){
				$post_list .= $key.'='.urlencode($val).'&';
			}
			$post_list = trim($post_list,'&');

			$ch=curl_init($url);
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_FAILONERROR, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
			// 后续的请求，使用前面得到的 cookies
			curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);


			// 新 session 的首次请求，保存得到的 cookies
			curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookieFile);
			curl_setopt($ch, CURLOPT_COOKIESESSION, true);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_list);

// 			curl_exec($ch);
			$resp = curl_exec($ch);
			$lastResp = array(
					'errno'		=> curl_errno($ch),
					'status'	=> curl_getinfo($ch, CURLINFO_HTTP_CODE),
					'resp'		=> $resp,
			);
			curl_close($ch);

			echo $resp;
		}

		public function post($url,$arr){
			$post_list = '';
			foreach($arr as $key => $val){
				$post_list .= $key.'='.urlencode($val).'&';
			}
			$post_list = trim($post_list,'&');

			$ch=curl_init($url);
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_FAILONERROR, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);

			// 后续的请求，使用前面得到的 cookies
			curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);
			// 新 session 的首次请求，保存得到的 cookies
// 			curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookieFile);
// 			curl_setopt($ch, CURLOPT_COOKIESESSION, true);
// 			curl_setopt($ch, CURLOPT_COOKIE, $this->cookie);

			curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_list);

			curl_exec($ch);
			$resp = curl_exec($ch);
			$lastResp = array(
					'errno'		=> curl_errno($ch),
					'status'	=> curl_getinfo($ch, CURLINFO_HTTP_CODE),
					'resp'		=> $resp,
			);
			$html = false;
			if ($lastResp['errno']) {
				$lastResp['error'] = curl_error($ch);
			} else {
				if ($lastResp['status'] === 200) {
					$html = $resp;
				}
			}
			curl_close($ch);
			return $html;
		}

		public function getCode($url){

			$value = file_get_contents('./value');
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch,CURLOPT_COOKIEJAR,$this -> cookieFile); //存储提交后得到的cookie数据
			curl_setopt($ch, CURLOPT_COOKIESESSION, true);

			$rs = curl_exec($ch);
			// 把验证码在本地生成，二次拉取验证码可能无法通过验证
			@file_put_contents("verify.jpg",$rs);
			curl_close($ch);

			header('location:http://localhost/login.html');
		}

		public function getValueState($url){
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_FAILONERROR, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);

			curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);

			// 后续的请求，使用前面得到的 cookies
			curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);

			curl_setopt($ch,CURLOPT_COOKIEJAR,$this -> cookieFile); //存储提交后得到的cookie数据
			curl_setopt($ch, CURLOPT_COOKIESESSION, true);

			$resp = curl_exec($ch);
			$lastResp = array(
					'errno'		=> curl_errno($ch),
					'status'	=> curl_getinfo($ch, CURLINFO_HTTP_CODE),
					'resp'		=> $resp,
			);
			$html = false;
			if ($lastResp['errno']) {
				$lastResp['error'] = curl_error($ch);
			} else {
				if ($lastResp['status'] === 200) {
					$html = $resp;
				}
			}
			curl_close($ch);

			$dom = str_get_html($html);

			$value = $dom -> find('#__VIEWSTATE');
			foreach($value as $val){
				if(!empty($val-> value)){
					$temp = $val->value;
					break;
				}
			}

			if(!empty($temp)){
				file_put_contents('./value', $temp);
			}
		}

		public function query($url){
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_FAILONERROR, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);

			if (!empty($this->headers)) {
				curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
			}

// 			curl_setopt($ch, CURLOPT_COOKIE, $this->cookie);
			curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

			$resp = curl_exec($ch);
			$lastResp = array(
					'errno'		=> curl_errno($ch),
					'status'	=> curl_getinfo($ch, CURLINFO_HTTP_CODE),
					'resp'		=> $resp,
			);

			$html = false;
			if ($lastResp['errno']) {
				$lastResp['error'] = curl_error($ch);
			} else {
				if ($lastResp['status'] === 200) {
					$html = $resp;
				}
			}
			curl_close($ch);
			return $resp;
		}

		public function getListUrl($url){
			$arr['__EVENTARGUMENT'] = $this -> now;
			$value = file_get_contents('./value');
			if(!empty($value)){
				$arr['__VIEWSTATE'] = $value;
			}
			$arr['__EVENTTARGET'] = 'AspNetPager1';
			$arr['AspNetPager1_input'] = 4;

			file_put_contents(ROOT_PATH.'data', '开始抓列表第'.$this->now."页:*********\r\n", FILE_APPEND);

			$html = $this -> post($url,$arr);

			if(empty($html)){
				file_put_contents(ROOT_PATH.'data', '抓列表第'.$this->now."页出错；\r\n", FILE_APPEND);
				return;
			}

			$html = str_get_html($html);
			$dom = $html -> find('td a');
			$arr = array();

			//获取详情页的地址
			foreach ($dom as $val){
				$url = $val -> getAttribute('href');
				if(!empty($url)){
					preg_match('/(\d+)\.html/',$url,$match);
					if(empty($match[1])) continue;
					$arr[] = $match[1];
				}
			}

			$value = $html -> find('#__VIEWSTATE');
			foreach($value as $val){
				if(!empty($val-> value)){
					$temp = $val->value;
					break;
				}
			}

			if(!empty($temp)){
				file_put_contents('./value', $temp);
			}else{
				//报错
				file_put_contents(ROOT_PATH.'data', "抓valueDate出错；\r\n", FILE_APPEND);
			}

			return $arr;
		}

		public function getDetail($uid){
			$url1 = 'http://www.tsrcw.com/hr/Resume/'.$uid.'.html';
			$url2 = 'http://www.tsrcw.com/hr/person/t1clxfs.aspx?id='.$uid;

			file_put_contents(ROOT_PATH.'data', "开始抓用户{$uid}:\r\n", FILE_APPEND);
			$html = $this -> query($url1);
			if(empty($html)){
				file_put_contents(ROOT_PATH.'data', "抓用户{$uid}失败；\r\n", FILE_APPEND);
				return;
			}

			$html = str_get_html($html);
			$dom = $html -> find('.cont_person .td_ll');
			$arr['uid'] = $uid;
			//获取姓名
			foreach ($dom as $val){
				$key = trim($val -> plaintext);

				switch($key){
					case '姓名':
						$arr['name'] = trim($val -> next_sibling() -> plaintext);
						break;
					case '性别':
						$arr['sex'] = trim($val -> next_sibling() -> plaintext);
						break;
					case '出生日期':
						$arr['birth'] = trim($val -> next_sibling() -> plaintext);
						break;
					case '工作经验':
						$arr['experience'] = trim($val -> next_sibling() -> plaintext);
						break;
					case '最高学历':
						$arr['education'] = trim($val -> next_sibling() -> plaintext);
						break;
					case '期望职位类别一':
					case '职位名称':
						if(empty($arr['career']))
							$arr['career'] = trim($val -> next_sibling() -> plaintext);
						break;
					case '联系电话':
						$arr['phone'] = intval($val -> next_sibling() -> plaintext);
						break;
				}

			}
			if(empty($arr['phone'])){
				$html = $this -> query($url2);
				if(empty($html)){
					return;
				}

				$html = str_get_html($html);
				$dom = $html -> find('.cont_person .td_ll');
				foreach ($dom as $val){
					$key = trim($val -> plaintext);

					switch($key){
						case '联系电话':
						case '手机':
							if(empty($arr['phone'])){
								$arr['phone'] = trim($val -> next_sibling() -> plaintext);
							}
							break;
						case 'QQ':
							$arr['qq'] = intval($val -> next_sibling() -> plaintext);
							break;
						case 'Email':
							$arr['Email'] = trim($val -> next_sibling() -> plaintext);
							break;
					}
				}
			}
			return $arr;
		}


		public function startQuery($url){
			while(true){
				//调用post接口，把列表页请求过来
				$list = $this -> getListUrl($url);
				if(!empty($list)){
					//进详情页把数据抓过来
					foreach($list as $val){
						$temp = $this -> getDetail($val);
						if(!empty($temp)){
							$resp = DB::insertOrDiscard(DB::tname('user'), $temp);
							if($resp){
								file_put_contents(ROOT_PATH.'data', '抓用户'.$temp['uid']."完成\r\n", FILE_APPEND);
							}else{
								file_put_contents(ROOT_PATH.'data', '抓用户'.$temp['uid']."失败\r\n", FILE_APPEND);
							}
						}
					}
				}else{
					break;
				}

				file_put_contents(ROOT_PATH.'data', '抓列表第'.$this->now."页完成*************\r\n", FILE_APPEND);
				$this -> now ++;
				break;
			}

		}
	}

	$mod = empty($_GET['mymodule'])?'':$_GET['mymodule'];

	$url = 'http://www.tsrcw.com/hr/company/search_list.aspx?er=1&0=&01=004&1=004&2=&3=&4=&5=&6=&7=1&8=&9=&10=&11=&12=&13=&14=7&15=&16=22&17=50';
	$loginUrl = 'http://www.tsrcw.com/hr/company/login.aspx';
	$getCodeUrl = 'http://www.tsrcw.com/hr/yzm/gif.aspx';
	$yzm = empty($_GET['yzm'])? '':$_GET['yzm'];


	$user = array(
		'username' => 'dexiang',
		'password' => '2187111',
		'Text_YZM' => $yzm,
		'Button1'  => '登 陆',
	);
	$value = file_get_contents('./value');
	if(!empty($value)){
		$user['__VIEWSTATE'] = $value;
	}
	$obj = new queryTSRC();
	$obj -> startQuery($url);
die;
// 	$obj -> getDetail(123052);
// $obj -> getListUrl('http://www.tsrcw.com/hr/company/search_list.aspx?%3fer=1&0=&01=&1=&2=&3=&4=&5=&6=&7=1&8=&9=&10=&11=&12=&13=&14=7&15=&16=0&17=0');

	switch ($mod){
		case 'index':
			$obj -> getValueState($loginUrl);
			$obj -> getCode($getCodeUrl);
			break;
		case 'query':
			$obj -> query();
			break;
		case 'login':
			$obj -> login($loginUrl,$user);
			break;
		default:
			$obj -> getValueState($loginUrl);
			$obj -> getCode($getCodeUrl);
	}
?>